<template>
  <page-header-wrapper>
    <a-row :gutter="24">
      <a-col :span="4">
        <a-card :bordered="false" class="ant-pro-components-tag-select" style="height: 800px">
          <a-input-search placeholder="请输入内容" @search="onSearch" />
          <a-tree :show-line="true"
                  :expanded-keys="expandedKeys"
                  :auto-expand-parent="autoExpandParent"
                  :tree-data="origintreedata"
                  @expand="onExpand"
                  @select="selecttree"
          >
          </a-tree>
        </a-card>
      </a-col>
      <a-col :span="20">
        <a-card :bordered="false">
          <div class="gtitle"><a-icon type="info-circle" style="color: #108ee9" theme="filled"/>资产分组维护及管理</div>
          <div style="margin-top: 30px;margin-bottom: 50px;">
            <a-button v-if="groupId != 14" type="primary" style="margin-right: 15px" @click="addsamelevel()">添加同级组</a-button>
            <a-button type="primary" style="margin-right: 15px" @click="addsublevel()">添加下级组</a-button>
            <a-button type="primary" style="margin-right: 15px" @click="modifygroupname()">修改组名称</a-button>
            <a-button v-if="groupId != 14" type="primary" style="margin-right: 15px" @click="deletegroup()">删除组</a-button>
            <a-button type="primary" style="margin-right: 15px">导入组织</a-button>
          </div>
          <div class="gtitle"><a-icon type="info-circle" style="color: #108ee9" theme="filled"/>资产自动分组匹配规则</div>
          <div style="margin-top: 30px;margin-bottom: 20px;">
            <a-button type="primary" style="margin-right: 15px" @click="createnewrule()">新建规则</a-button>
            <a-button type="primary" style="margin-right: 15px" @click="modifyrule()">修改规则</a-button>
            <a-button type="primary" style="margin-right: 15px " @click="deleterule()">删除规则</a-button>
            <a-button type="primary" style="margin-right: 15px" @click="setrule()">开启/关闭规则</a-button>
          </div>

          <a-table :columns="columns" :data-source="tabledata" :row-selection="rowSelection" :pagination="tablepagination" @change="tablechange">
            <template slot="index" slot-scope="text, record,index">{{index+1}}</template>
            <template slot="policyStatus" slot-scope="text, record">
              <a-tag v-if="text == 0" color="red">{{OnOffMap[text]}}</a-tag>
              <a-tag v-if="text == 1" color="green">{{OnOffMap[text]}}</a-tag>
            </template>
            <template slot="priority" slot-scope="text, record">
              <a-tag v-if="text == 0" color="#52c41a">{{PriorityMap[text]}}</a-tag>
              <a-tag v-if="text == 1" color="#1890ff">{{PriorityMap[text]}}</a-tag>
              <a-tag v-if="text == 2" color="#f5222d">{{PriorityMap[text]}}</a-tag>
            </template>
            <template slot="establishTime" slot-scope="text, record">
              {{text?text.replace('T',' '):''}}
            </template>
            <template slot="matchRules" slot-scope="text, record">
              <div  v-for="item in JSON.parse(text).ip">
                {{item.value}}
              </div>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <Mymodal
      ref="mymodal"
    ></Mymodal>
  </page-header-wrapper>
</template>
<script>
import Mymodal from '@/components/mycomp/mymodal.vue'
import { getDepartmentList } from '@/api/department'
import { getrulelist, addassetsgroup, deletegroup, addrule, deleterule,setpolicyStatus } from '@/api/assets'
import {OnOff,OnOffMap,Priority,PriorityMap} from '../../utils/constant'
export default {
  name: 'AssetGrouping',
  components: { Mymodal },
  data() {
    return {
      OnOff,
      OnOffMap,
      Priority,
      PriorityMap,
      /** 树**/
      expandedKeys:[],
      autoExpandParent:true,
      treedata:[],
      origintreedata:[],
      groupId:'',
      pId:'',
      groupMap:{},
      /** 树**/

      /** 表**/
      columns:[
        {
          title: '#',
          dataIndex: 'index',
          key: 'index',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '资产分组名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '规则优先级',
          dataIndex: 'priority',
          key: 'priority',
          scopedSlots: { customRender: 'priority' },
        },
        {
          title: '策略状态',
          dataIndex: 'policyStatus',
          key: 'policyStatus',
          scopedSlots: { customRender: 'policyStatus' },
        },
        {
          title: '匹配组',
          dataIndex: 'groupName',
          key: 'groupName',
        },
        {
          title: '自动匹配IP',
          dataIndex: 'matchRules',
          key: 'matchRules',
          scopedSlots: { customRender: 'matchRules' },
        },
        {
          title: '规则建立时间',
          dataIndex: 'establishTime',
          key: 'establishTime',
          scopedSlots: { customRender: 'establishTime' },
        },
      ],
      tabledata:[],
      rowSelection:{
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectarray = selectedRows
          document.getElementById('app').style.transform = `scale(1)`
          document.getElementById('app').style.transformOrigin = `0 0`
          document.getElementById('app').style.height = `100%`
          setTimeout(()=>{
            var scale = (window.innerWidth-20)/1900
            document.getElementById('app').style.transform = `scale(${scale})`
            document.getElementById('app').style.transformOrigin = `0 0`
            document.getElementById('app').style.height = `${100/scale}%`
          },0)
        },
        onSelect: (record, selected, selectedRows) => {
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
        },
      },
      tablepagination:{
        showTotal:(total, range) => {return `共搜索到${total}条数据`},
        current:1,
        total:0
      },
      selectarray:null
      /** 表**/
    }
  },
  mounted() {
    this.getrulelist()
    this.loaddepartment()
  },
  methods: {
    tablechange(pagination){
      this.tablepagination = pagination
      this.getrulelist()
    },
    createnewrule(){
      let modalinfo = {
        title:'新建规则',
        list:[
          {name:'name',label:'规则名称',require:true,type:'input',errortip:'请输入名称'},
          {name:'priority',label:'规则优先级',type:'select',selectdata:this.Priority,require: true,errortip: '请选择规则优先级'},
          {name:'dsc',label:'规则备忘描述',type:'textarea',errortip:'请输入名称'},
          {name:'groupId',label:'选择资产组',require:true,type:'tree',errortip:'请选择部门',treedata:this.treedata},
          {name:'matchRules',label:'匹配条件',type:'iplist'},
        ],
        ok:this.createruleokfun.bind(this),
      }
      this.$refs.mymodal.showmodal(modalinfo)

    },
    createruleokfun(params){
      addrule(params).then(res=>{
        this.getrulelist()
      })
    },
    modifyrule(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      if(this.selectarray && this.selectarray.length >1){
        this.$message.info('此操作只支持一条数据')
        return
      }
      let item = this.selectarray[0]

      let modalinfo = {
        title:'修改规则',
        list:[
          {name:'name',label:'规则名称',require:true,type:'input',errortip:'请输入名称',value:item.name},
          {name:'priority',label:'规则优先级',type:'select',selectdata:this.Priority,require: true,errortip: '请选择规则优先级',value:item.priority.toString()},
          {name:'dsc',label:'规则备忘描述',type:'textarea',errortip:'请输入名称',value:item.dsc},
          {name:'groupId',label:'选择资产组',require:true,type:'tree',errortip:'请选择部门',treedata:this.treedata,value:item.groupId},
          {name:'matchRules',label:'匹配条件',type:'iplist',value:item.matchRules},
        ],
        ok:this.createruleokfun.bind(this),
        moreinfo:{
          id:item.id
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },
    addsamelevel(){
      if(!this.groupId){
        this.$message.info('请先选择一个分组')
        return
      }

      let modalinfo = {
        title:'新建分组',
        list:[
          {name:'name',label:'分组名称',require:true,type:'input',errortip:'请输入名称'},
        ],
        ok:this.createdepartok.bind(this),
        moreinfo:{
          pId:this.pId
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },
    setrule(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      let id = this.getids()

      let modalinfo = {
        title:'开启/关闭规则',
        list:[
          {name:'policyStatus',require:true,label:'开启/关闭',type:'select',selectdata:this.OnOff,errortip:'请选择状态'},
        ],
        ok:this.setpok.bind(this),
        moreinfo:{
          id:id
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },
    setpok(params){
      setpolicyStatus(params).then(res=>{
        this.getrulelist()
      })
    },



    addsublevel(){
      if(!this.groupId){
        this.$message.info('请先选择一个分组')
        return
      }

      let modalinfo = {
        title:'新建分组',
        list:[
          {name:'name',label:'分组名称',require:true,type:'input',errortip:'请输入名称'},
        ],
        ok:this.createdepartok.bind(this),
        moreinfo:{
          pId:this.groupId
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },

    createdepartok(params){
      addassetsgroup(params).then(res=>{
        this.loaddepartment()
      })

    },
    deleterule(){
      if(!this.selectarray || this.selectarray.length == 0){
        this.$message.info('请先选择一条数据')
        return
      }
      let id = this.getids()

      this.$confirm({
        title: '是否确认删除数据?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk:()=> {
          deleterule({id:id}).then(res=>{
            this.getrulelist()
          })
        }
      });
    },

    modifygroupname(){
      if(!this.groupId){
        this.$message.info('请先选择一个分组')
        return
      }

      let modalinfo = {
        title:'修改分组',
        list:[
          {name:'name',label:'分组名称',require:true,type:'input',errortip:'请输入名称',value:this.groupMap[this.groupId].title},
        ],
        ok:this.createdepartok.bind(this),
        moreinfo:{
          pId:this.groupMap[this.groupId].pId,
          id:this.groupId
        }
      }
      this.$refs.mymodal.showmodal(modalinfo)
    },


    deletegroup(){
      if(!this.groupId){
        this.$message.info('请先选择一个分组')
        return
      }

      this.$confirm({
        title: '是否确认删除数据?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk:()=> {
          deletegroup({ids:this.groupId}).then(res=>{
            if(res.code!=200){
              this.$message.error(res.message)
            }else{
              this.groupId = ''
              this.loaddepartment()
              this.getrulelist()
            }

          })
        }
      });

    },


    /**表**/
    getrulelist(){
      let params = {}
      params.pageNo = this.tablepagination.current
      params.pageSize = 10
      params.groupId = this.groupId

      getrulelist(params).then(res=>{
        let record = res.data.records
        for(let i in record){
          record[i].key =record[i].id
        }
        this.tabledata = record
        this.tablepagination.total = res.data.total
      })
    },
    getids(){
      let arry = []
      for(let i in this.selectarray){
        arry.push(this.selectarray[i].id)
      }
      let id = arry.join(',')
      return id
    },
    /**表**/


    /**树 **/
    getParentKey(key, tree){
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key;
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    getallnode(list){
      let array = []
      for(let i =0;i<list.length;i++){
        array.push(list[i])
        if(list[i].children){
          array = array.concat(this.getallnode(list[i].children))
        }
      }
      return array
    },
    onSearch(value) {
      let list = this.getallnode(this.treedata)
      let expandedKeys1 = list
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key, this.treedata);
          }
          return null;
        })
      let expandedKeys = expandedKeys1
        .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    selecttree(key,e){
      if(e.node.$parent.value){
        this.pId = e.node.$parent.value
      }else{
        this.pId = 0
      }
      this.groupId = key[0]
      this.getrulelist()
    },
    loaddepartment(){
      getDepartmentList({isHaveWhole:1}).then(res=>{
        this.groupMap = {}
        if(res.data){
          this.origintreedata = this.transtotree(res.data)
          this.treedata = this.origintreedata[0].children
          let list = this.getallnode(this.treedata)
          for(let i in list){
            this.groupMap[list[i].key] = list[i]
          }
        }
      })
    },
    transtotree(list){
      let arry = []
      for(let i in list){
        let json = {}
        json.title = list[i].name
        json.key = list[i].id
        json.value = list[i].id
        json.pid = list[i].pId
        if(list[i].childNode){
          json.children = this.transtotree(list[i].childNode)
        }
        arry.push(json)
      }
      return arry
    },
    /** 树**/
  },
}
</script>

<style lang="less" scoped>
.gtitle{
  background-color: #e6f3fc;
  line-height: 40px;
  padding-left: 20px;
  color: #333;
  font-weight: bold;
  i{
    margin-right: 10px;
  }
}
</style>
